<template>
  <div class="resultPage">
    <basic-container v-show="isTable">
      <avue-crud :option="option"
        :table-loading="loading"
        :data="data"
        :page="page"
        ref="crud"
        v-model="form"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <el-button size="small" icon="el-icon-download" :loading="groupLoading" @click="handleExportGroup">导出团体报告</el-button>
          <el-button size="small" icon="el-icon-download" :loading="personageLoading" @click="handleExportPersonage">批量导出个人报告</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button type="text" size="small" @click="handleSee(scope.row)">查看报告</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <div class="result" v-show="!isTable" ref="result">
      <header>
        <el-button type="warning" icon="el-icon-back" size="small" @click.stop="gobackList">返回列表</el-button>
        <el-button type="warning" :loading="exportLoading" icon="el-icon-download" size="small" @click.stop="handlerExport">导出报告</el-button>
      </header>
      <el-tabs v-model="activeName" @tab-click="handleClickTab">
        <el-tab-pane label="结果报告" name="first">
          <Titlebold><i class="el-icon-user-solid"></i>基本信息</Titlebold>
          <el-descriptions column="4" border>
              <el-descriptions-item label="量表">{{ basicInfo.templateName }}</el-descriptions-item>
              <el-descriptions-item label="学校">{{ basicInfo.schoolName}}</el-descriptions-item>
              <el-descriptions-item label="年级">{{ basicInfo.njName}}</el-descriptions-item>
              <el-descriptions-item label="班级">{{ basicInfo.bjName}}</el-descriptions-item>
              <el-descriptions-item label="学生学号">{{ basicInfo.studetnNo }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{ basicInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ basicInfo.sex }}</el-descriptions-item>
              <el-descriptions-item label="测试时间">{{ basicInfo.testTime }}</el-descriptions-item>
          </el-descriptions>
          <Titlebold style="margin-top: 20px;"><i class="el-icon-pie-chart"></i>图表</Titlebold>
          <div class="divisorChart" ref="divisorChart"></div>
          <Titlebold style="margin-top: 20px;"><i class="el-icon-notebook-1"></i>结果解释</Titlebold>
          <el-empty v-if="resultExplain.length == 0" description="无数据"></el-empty>
          <div class="tableContainer" v-else>
            <div class="tableInfo" v-for="(item) of resultExplain" :key="item.value">
              <div class="left">{{ item.key }}</div>
              <div class="right">{{ item.value }}</div>
            </div>
          </div>
          <Titlebold style="margin-top: 20px;"><i class="el-icon-chat-line-round"></i>建议</Titlebold>
          <el-empty v-if="suggest.length == 0" description="无数据"></el-empty>
          <div class="tableContainer" v-else>
            <div class="tableInfo" v-for="(item) of suggest" :key="item.value">
              <div class="left">{{ item.key }}</div>
              <div class="right">{{ item.value }}</div>
            </div>
          </div>
          <Titlebold style="margin-top: 20px;"><i class="el-icon-s-grid"></i>因子分数表</Titlebold>
          <el-table
            :data="scaleData"
            stripe
            style="width: 100%;margin-bottom: 270px;">
            <el-table-column label="序号" header-align="center" align="center" width="60" type="index"></el-table-column>
            <el-table-column prop="scaleName" header-align="center" align="center" label="因子名称"></el-table-column>
            <el-table-column prop="scaleScore" header-align="center" align="center" label="因子分"></el-table-column>
            <el-table-column prop="scaleGrade" header-align="center" align="center" label="等级"></el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="作答详情" name="second">
          <el-table
            :data="answerInDetailsDtos"
            stripe
            style="width: 100%;margin-bottom: 270px;">
            <el-table-column prop="serial" header-align="center" align="center" label="序号"></el-table-column>
            <el-table-column prop="answer" header-align="center" align="center" label="答案"></el-table-column>
            <el-table-column prop="score" header-align="center" align="center" label="得分"></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
import { getSchoolTree } from "@/api/platform/psychologyQuestionnaire";
import { getResultList, getSchoolTempList, getPersonalReport, exportPersonalReport, exportGroupReport, exportPersonalReportBatch } from "@/api/platform/templateManage";
import { grade } from "@/api/service/xs";

import Titlebold from './titlebold'
import * as echarts from 'echarts';

export default {
  components:{Titlebold},
  data() {
    return {
      form: {},
      loading: false,
      selectionList: [],
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      data: [],
      option: {
        // height: 'auto',
        searchShow: true,
        searchMenuSpan: 6,
        tree: false,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: false,
        menuWidth: 100,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        column: [
          {
            label: "学校",
            prop: "schoolId",
            search: true,
            type: 'tree',
            dicData: [],
            rules: [
              {
                required: true,
                message: "请选择学校",
                trigger: "blur"
              }
            ],
            props: {
              label: "xxName",
              value: "id"
            },
            cascader: ['jdId'],
            change: ({value}) => {
              this.schoolTypeChange(value);
            }
          },
          {
            label: "所属阶段",
            prop: "jdId",
            type: "select",
            search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请选择所属阶段",
              trigger: "blur"
            }],
            hide: true,
            dicUrl: "/api/ManageStudent/GetSchoolStageSelect",
            cascader: ['njId'],
            props: {
              label: "title",
              value: "id"
            },
            change: ({value}) => {
              this.jdIdTypeChange(value);
            }
          },
          {
            label: "年级",
            prop: "njId",
            type: "select",
            search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入年级名称",
              trigger: "blur"
            }],
            props: {
              label: "title",
              value: "id"
            },
            cascader: ['bjId'],
            dicData: [],
            formatter: (row) =>{
              return row.njName
            }
          },
          {
            label: "班级",
            prop: "bjId",
            search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入班级",
              trigger: "blur"
            }],
            type: "select",
            dicUrl: "/api/ManageStudent/GetClassSelect?njId={{key}}",
            props: {
              label: "bjName",
              value: "id"
            },
            formatter: (row) =>{
              return row.bjName
            }
          },
          {
            label: "学号",
            prop: "studetnNo",
          },
          {
            label: "姓名",
            prop: "xsName",
            search: true,
            formatter: row => {
              return row.name
            }
          },
          {
            label: "性别",
            prop: "sex",
            type: "select",
            dicData: [
              {
                label: '男',
                value: 1,
              },
              {
                label: '女',
                value: 2,
              }
            ],
            search: true
          },
          {
            label: "年龄",
            prop: "age",
          },
          {
            label: "量表",
            prop: "templateId",
            type: 'select',
            props: {
              label: 'title',
              value: 'id'
            },
            search: true
          },
          {
            label: "测评时间",
            prop: "testTime",
          },
          {
            label: "用时",
            prop: "takeTime",
          },
          {
            label: "结果",
            prop: "result",
            type: 'select',
            // search: true,
            dicData: [
              {
                label: '正常',
                value: false
              },
              {
                label: '异常',
                value: true
              }
            ]
          },
          {
            label: "状态",
            prop: "state",
            type: 'select',
            dicData: [
              {
                label: '有效',
                value: true
              }, {
                label: '无效',
                value: false
              }
            ]
          },
          {
            label: "状态",
            prop: "status",
            type: 'select',
            search: true,
            hide: true,
            value: 0,
            dicData: [
              {
                label: '有效',
                value: 1
              }, {
                label: '无效',
                value: 2
              }
            ]
          },
          {
            prop: 'StartTime',
            label: '开始时间',
            search: true,
            type: 'date',
            valueFormat: 'yyyy-MM-dd',
            hide: true
          },
          {
            prop: 'EndTime',
            label: '结束时间',
            search: true,
            type: 'date',
            valueFormat: 'yyyy-MM-dd',
            hide: true
          }
        ]
      },
      isTable: true,
      activeName: 'first',
      // tabInfo: [
      //   {
      //     left: '学习压力源总均分',
      //     right: '你的分数为452分，表示你当前承受的学业压力处于较高水平，具体表现为你在学习活动中承受了较大的精神负担，出现焦虑、紧张、无力的感觉，这甚至影响到学业以外的其他方面亲子关系变差等等，你需要付出非常大的努力去应对和解决学业带来的压力感。'
      //   },
      //   {
      //     left: '学习压力源总均分',
      //     right: '你的分数表示你当前承受的学业压力处于较高水平表示你当前承受的学业压力处于较高水平为452分，表示你当前承受的学业压力处于较高水平，具体表现为你在学习活动中承受了较大的精神负担，出现焦虑、紧张、无力的感觉，这甚至影响到学业以外的其他方面亲子关系变差等等，你需要付出非常大的努力去应对和解决学业带来的压力感。'
      //   },
      //   {
      //     left: '学习压力源总均分',
      //     right: '你的分数为452分，表示你当前承受的学业压力处于较高水平，具体表现为你在学习活动中承受了较大的精神负担，出现焦虑、紧张、无力的感觉，这甚至影响到学业以外的其他方面亲子关系变差等等，你需要付出非常大的努力去应对和解决学业带来的压力感。'
      //   },{
      //     left: '学习压力源总均分',
      //     right: '表示你当前承受的学业压力处于较高水平表示你当前承受的学业压力处于较高水平你的分数为452分，表示你当前承受的学业压力处于较高水平，具体表现为你在学习活动中承受了较大的精神负担，出现焦虑、紧张、无力的感觉，这甚至影响到学业以外的其他方面亲子关系变差等等，你需要付出非常大的努力去应对和解决学业带来的压力感。'
      //   }

      // ],
      schoolId: '',
      basicInfo: {
        templateName: '',
        schoolName: '',
        njName: '',
        bjName: '',
        studetnNo: '',
        name: '',
        sex: '',
        testTime: '',
      },
      resultExplain: [],
      suggest: [],
      scaleData: [],
      chartData: [],
      answerInDetailsDtos: [],
      rowId: '0',
      exportLoading: false,
      mychart: null,
      groupLoading: false,
      personageLoading: false
    }
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.scaleResultId);
      });
      return ids.join(",");
    }
  },
  methods: {
    getTree() {
      getSchoolTree().then(res => {
        const column = this.findObject(this.option.column, "schoolId");
        column.dicData = res.data.data;
        this.treeSchoolData = res.data.data;
      })
    },
    schoolTypeChange(v) {
      this.schoolId = v
    },
    jdIdTypeChange(v) {
      if (this.schoolId !== "" && this.schoolId !== null && this.schoolId !== undefined) {
        let params = {
          schoolId: this.schoolId,
          jdId: v
        }
        grade(params).then(res => {
          const gradeData = this.findObject(this.option.column, "njId");
          gradeData.dicData = res.data.data
        });
      }
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      const d = {
        current: page.currentPage,
        size: page.pageSize,
        ...Object.assign(params, this.query)
      }
      getResultList(d).then(res => {
        this.loading = false;
        this.page.total = res.data.data.total;
        this.data = res.data.data.records;
      })
      this.getTree()
      this.getTempList()
    },
    getTempList() {
      getSchoolTempList().then(res => {
        const scale = this.findObject(this.option.column, "templateId");
        scale.dicData = res.data.data;
      })
    },
    handleSee(row) {
      this.rowId = row.scaleResultId
      this.isTable = false
      this.$nextTick(() => {
        this.$refs.result.scrollIntoView()
        this.mychart = echarts.init(this.$refs.divisorChart)
        this.mychart.clear()
      })
      this.basicInfo = {
        templateName: row.templateName,
        schoolName: row.schoolName,
        njName: row.njName,
        bjName: row.bjName,
        studetnNo: row.studetnNo,
        name: row.name,
        sex: row.sex,
        testTime: row.testTime,
      }
      getPersonalReport({ scaleResultId: row.scaleResultId }).then(res => {
        const d = res && res.data && res.data.data;
        this.resultExplain = d.resultExplainDtos
        this.suggest = d.resultSuggestDtos
        this.scaleData = d.scaleScoreDtos
        this.chartData = d.histogramDtos.length > 0 ? d.histogramDtos : d.totalityHistogramDtos
        this.answerInDetailsDtos = d.answerInDetailsDtos
      }).then(() => {
        const xData = this.chartData.map(item=>item.key)
        // const values = this.chartData.map(item=>item.value)
        const series = this.chartData.map((item, ind) => {
          let arr = new Array(xData.length).fill(null)
          arr[ind] = item.value
          let obj = {
            name: item.key,
            type: 'bar',
            data: arr
          }
          // this.chartData.length == 1 ?  obj.barWidth =  '30%' : ''
          return obj
        })
        this.$nextTick(() => {
          const option = {
            title: {
              // text: '压力测试'
            },
            tooltip: {},
            legend: {
              // data:["任务要求压力","竞争压力","挫折压力","期望压力","发展压力"]
              // data: xData
            },
            xAxis: {
              // data: ["任务要求压力","竞争压力","挫折压力","期望压力","发展压力"]
              data: xData
            },
            yAxis: {},
            // series: [{
            //   // name: '分值',
            //   type: 'bar',
            //   // data: [5, 20, 36, 10, 10, 20]
            //   data: values
            // }]
            series: series
          };
          this.mychart.setOption(option);
        })
      })
    },
    gobackList() {
      this.isTable = true
      this.basicInfo = {
        templateName: '',
        schoolName: '',
        njName: '',
        bjName: '',
        studetnNo: '',
        name: '',
        sex: '',
        testTime: '',
      }
      this.resultExplain = []
      this.suggest = []
      this.scaleData = []
      this.chartData = []
      this.answerInDetailsDtos = []
      this.activeName = 'first'
      this.query = {}
      this.rowId = '0'
    },
    // personexport
    handlerExport() {
      this.exportLoading = true
      exportPersonalReport({ scaleResultId: this.rowId }).then(res => {
        const link = res.data.data
        if (link) {
          const a = document.createElement('a')
          a.href = link
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      }).finally(() => {
        this.exportLoading = false
      })
    },
    handleExportGroup() {
      if (!this.query.templateId) {
        this.$message.warning('请先至少选择量表筛选条件！！！')
        return
      }
      this.groupLoading = true
      exportGroupReport(this.query).then(res => {
        if (res.data.code == 200) {
          const d = res.data.data
          d.split(',').forEach((a, ind) => {
            setTimeout(() => {
              const link = document.createElement('a')
              link.href = a
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link)
            }, ind*1500)
          })
        }
      }).finally(() => {
        this.groupLoading = false
      })
    },
    handleExportPersonage() {
      if (!this.query.bjId) {
        this.$message.warning('请选择班级并搜索')
        return
      }
      if (!this.query.templateId) {
        this.$message.warning('请选择量表并搜索')
        return
      }
      if (this.ids.length == 0) {
        this.$message.warning('请在列表左侧勾选学生')
        return
      }
      this.personageLoading = true
      exportPersonalReportBatch({ ids: this.ids }).then(res => {
        const a = res.data.data
        const link = document.createElement('a')
        link.href = a
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.selectionList = []
        this.$refs.crud.toggleSelection();
      }).finally(() => {
        this.personageLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.result{
  height: 100%;
  background-color: #fff;
  box-sizing: border-box;
  padding: 0 20px;
}
.divisorChart{
  width: 100%;
  height: 400px;
}
.tableContainer{
  width: 100%;
  margin-bottom: 10px;
}
.tableInfo{
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  color: #63707f;
  font-size: 14px;
  // font-family: 'Courier New', Courier, monospace;
  // font-family: '黑体';
  line-height: 20px;
  .left{
    width: 15%;
    flex-shrink: 0;
  }
}
</style>
